<template>
  <div class="app-container">
    <el-card>
      <!-- 标题 -->
      <div slot="header" class="clearfix">
        <span>学生成绩趋势分析</span>
      </div>
      <!-- 选择器 -->
      <div class="selector-container">
        <!-- 专业输入 -->
        <el-autocomplete
          v-model="majorId"
          :fetch-suggestions="queryMajor"
          placeholder="请输入专业ID"
          @select="handleMajorSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>
        <!-- 班级输入 -->
        <el-autocomplete
          v-model="classId"
          :fetch-suggestions="queryClass"
          placeholder="请输入班级ID"
          @select="handleClassSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>
        <!-- 学生输入 -->
        <el-autocomplete
          v-model="studentId"
          :fetch-suggestions="queryStudent"
          placeholder="请输入学号"
          @select="handleStudentSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>
        <!-- 查询按钮 -->
        <el-button type="primary" title="查询成绩趋势" @click="fetchData">查询</el-button>
      </div>
      <!-- 图表展示 -->
      <div v-if="loading" class="loading-container">
        <span>正在加载数据，请稍候...</span>
      </div>
      <div v-else class="chart-container">
        <div ref="trendChart" class="chart" />
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getTrendByStudent,
  getTrendByClass,
  getTrendByMajor
} from '@/api/teacher'

export default {
  name: 'ScoreTrendAnalysis',
  data() {
    return {
      // 输入框绑定值
      majorId: '',
      selectedMajorId: '',
      classId: '',
      selectedClassId: '',
      studentId: '',
      selectedStudentId: '',
      displayData: null, // 新增：用于展示的数据
      // 自动补全选项
      majorOptions: [
        { label: '计算机科学与技术', value: 'CS' },
        { label: '软件工程', value: 'SE' }
      ],
      classOptions: [],
      studentOptions: [],

      // 趋势数据
      studentTrend: [],
      classTrend: [],
      majorTrend: [],

      loading: false
    }
  },
  created() {
    // 模拟原始数据输入（可以从接口获取）
    const rawMajorData = `
major1,college1,计科
major2,college1,AI
major3,college1,大数据
major4,college1,物联
major5,college1,通信
major6,college1,电子
major7,college1,计算机类
major8,college1,曙光
major9,college1,电信类
major10,college1,建筑类
  `.trim().split('\n')

    const rawClassData = `
class126,major1,计科2401班
class104,major1,计科2402班
class41,major1,计科2403班
class111,major1,计科2404班
class86,major2,AI2401班
class121,major2,AI2402班
  `.trim().split('\n')

    const rawStudentData = `

  `.trim().split('\n')
    // 自动生成映射表
    this.generateMappings(rawMajorData, rawClassData, rawStudentData)
  },
  methods: {
    generateMappings(majors, classes, students) {
      // 专业映射
      this.majorOptions = []
      this.classOptions = []
      this.studentOptions = []
      // 保存专业ID到中文名的映射
      const majorIdToLabel = {}
      // 解析专业数据
      majors.forEach(line => {
        // eslint-disable-next-line no-unused-vars
        const [id, _, label] = line.split(',')
        majorIdToLabel[id.trim()] = label.trim()
        this.majorOptions.push({ label: label.trim(), value: id.trim() })
      })
      // 解析班级数据
      const classMap = {}
      const classDisplayNames = {} // 新增：保存班级ID到中文名称的映射
      classes.forEach(line => {
        const [classId, majorId, className] = line.split(',')
        if (!classMap[majorId]) classMap[majorId] = []
        classMap[majorId].push(classId.trim())
        classDisplayNames[classId.trim()] = className.trim() // 存储映射关系
        this.classOptions.push({ label: className.trim(), value: classId.trim() })
      })
      // 挂载到 Vue 实例供后续使用
      this.classDisplayNames = classDisplayNames
      // 解析学生数据
      const studentMap = {}
      students.forEach(line => {
        const [studentId, classId, name] = line.split(',')
        if (!studentMap[classId]) studentMap[classId] = []
        studentMap[classId].push(studentId.trim())
        this.studentOptions.push({ label: `${name}(${studentId})`, value: studentId.trim() })
      })
      // 存储映射关系供后续使用
      this.classMap = classMap
      this.studentMap = studentMap
      this.majorIdToLabel = majorIdToLabel
    },
    // 专业输入搜索
    queryMajor(queryString, cb) {
      const results = this.majorOptions.filter(item => {
        return (
          item.label.includes(queryString) ||
          item.value.includes(queryString)
        )
      })
      cb(results)
    },
    // 班级输入搜索
    queryClass(queryString, cb) {
      const results = this.classOptions.filter(item => {
        return (
          item.label.includes(queryString) ||
          item.value.includes(queryString)
        )
      })
      cb(results)
    },
    // 学生输入搜索
    queryStudent(queryString, cb) {
      const results = this.studentOptions.filter(item => {
        return (
          item.label.includes(queryString) ||
          item.value.includes(queryString)
        )
      })
      cb(results)
    },
    // 专业选择回调
    handleMajorSelect(item) {
      this.majorId = item.label
      this.selectedMajorId = item.value
      this.classId = ''
      this.studentId = ''
      this.fetchClassOptions(item.value)
    },
    // 班级选择回调
    handleClassSelect(item) {
      this.classId = item.label
      this.selectedClassId = item.value
      this.studentId = ''
      this.fetchStudentOptions(item.value)
    },
    // 学生选择回调
    handleStudentSelect(item) {
      this.studentId = item.label
      this.selectedStudentId = item.value
    },
    // 获取班级选项
    fetchClassOptions(majorId) {
      const classes = this.classMap[majorId] || []
      this.classOptions = classes.map(id => ({
        label: this.classDisplayNames[id] || id, // 使用中文名称作为 label
        value: id
      }))
    },
    // 获取学生选项
    fetchStudentOptions(classId) {
      const students = this.studentMap[classId] || []
      this.studentOptions = students.map(id => ({
        label: `学号 ${id}`,
        value: id
      }))
    },
    // 获取数据
    // 在 methods 中修改 fetchData() 方法如下
    async fetchData() {
      if (!this.majorId && !this.classId && !this.studentId) {
        this.$message.warning('请至少选择专业、班级或学生')
        return
      }

      this.loading = true
      try {
        const promises = []

        if (this.selectedStudentId) promises.push(getTrendByStudent(this.selectedStudentId))
        if (this.selectedClassId) promises.push(getTrendByClass(this.selectedClassId))
        if (this.selectedMajorId) promises.push(getTrendByMajor(this.selectedMajorId))

        console.log('发起请求参数:', {
          studentId: this.studentId,
          classId: this.classId,
          majorId: this.majorId
        })

        const responses = await Promise.all(promises)

        // 清空旧数据
        this.studentTrend = []
        this.classTrend = []
        this.majorTrend = []

        const allData = [] // 用于收集所有数据

        responses.forEach((res, index) => {
          console.log('接口响应:', res)
          if (res && res.success && res.data && Array.isArray(res.data)) {
            const trendData = res.data
            if (this.studentId && index === 0) {
              this.studentTrend = trendData
              allData.push({ type: '学生', data: trendData })
            } else if (this.classId && index === (this.studentId ? 1 : 0)) {
              this.classTrend = trendData
              allData.push({ type: '班级', data: trendData })
            } else {
              this.majorTrend = trendData
              allData.push({ type: '专业', data: trendData })
            }
          } else {
            this.$message.warning('部分数据加载失败')
            console.warn('接口数据异常:', res)
          }
        })

        this.displayData = allData // 将所有数据赋值给 displayData

        // 确保 DOM 更新完成后再渲染图表
        this.$nextTick(() => {
          this.renderChart()
        })
      } catch (error) {
        console.error('请求失败详情:', error.response || error.message)
        this.$message.error('数据加载失败，请检查网络或联系后端')
      } finally {
        this.loading = false
      }
    },
    // 在 fetchData 方法调用 renderChart() 时，更新以下 option 配置
    renderChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.trendChart
        if (!chartDom) {
          console.warn('图表容器未找到，请检查 DOM')
          return
        }

        const chart = echarts.init(chartDom)

        // 构建数据系列
        const series = []
        const legends = []

        // 添加学生趋势
        if (this.studentTrend.length > 0) {
          series.push({
            name: '学生本人',
            type: 'line',
            data: this.studentTrend.map(item => item.trendValue),
            lineStyle: { color: '#f8ac8c' },
            showSymbol: true,
            markLine: {
              data: [{ type: 'average', name: '平均值' }],
              label: { show: true },
              lineStyle: { color: '#f8ac8c', width: 1, type: 'dashed' }
            }
          })
          legends.push('学生本人')
        }

        // 添加班级趋势
        if (this.classTrend.length > 0) {
          series.push({
            name: '所在班级',
            type: 'line',
            data: this.classTrend.map(item => item.trendValue),
            lineStyle: { color: '#91cc75' },
            showSymbol: false,
            markLine: {
              data: [{ type: 'average', name: '平均值' }],
              label: { show: true },
              lineStyle: { color: '#91cc75', width: 1, type: 'dashed' }
            }
          })
          legends.push('所在班级')
        }

        // 添加专业趋势
        if (this.majorTrend.length > 0) {
          series.push({
            name: '所在专业',
            type: 'line',
            data: this.majorTrend.map(item => item.trendValue),
            lineStyle: { color: '#5470c6' },
            showSymbol: false,
            markLine: {
              data: [{ type: 'average', name: '平均值' }],
              label: { show: true },
              lineStyle: { color: '#5470c6', width: 1, type: 'dashed' }
            }
          })
          legends.push('所在专业')
        }

        // 构建X轴数据（以第一个非空趋势的学期为准）
        const firstValidTrend = this.studentTrend.length
          ? this.studentTrend
          : this.classTrend.length
            ? this.classTrend
            : this.majorTrend || []
        const xAxisData = firstValidTrend.map(item => item.semester)

        // 配置选项
        const option = {
          title: {
            text: '学生成绩趋势分析',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: legends,
            top: '10%'
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            name: '学期'
          },
          yAxis: {
            type: 'value',
            name: '加权平均成绩',
            min: 0,
            max: 100,
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#ccc'],
                width: 1,
                type: 'dashed'
              }
            }
          },
          series: series,
          graphic: {
            elements: [{
              type: 'text',
              left: 'center',
              bottom: 20,
              style: {
                text: '加权平均成绩 = Σ（课程成绩 × 对应学分） / Σ总学分',
                fontSize: 12,
                textAlign: 'center',
                fill: '#666'
              }
            }]
          }
        }
        chart.setOption(option, true)
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.selector-container {
  margin-bottom: 30px;
  display: flex;
  gap: 20px;
}

.chart-container {
  width: 100%;
  height: 500px;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading-container {
  padding: 20px;
}

.autocomplete-item {
  padding: 10px;
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
}
</style>
